package test.functionQuery.functionsort;

import org.apache.lucene.queries.function.ValueSource;
import org.apache.solr.common.SolrException;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.schema.TrieDateField;
import org.apache.solr.search.FunctionQParser;
import org.apache.solr.search.SyntaxError;
import org.apache.solr.search.ValueSourceParser;

/**
 * Created by chenbingwen on 18/1/19.
 */
public class CompanyFunctionSortSoruceParser extends ValueSourceParser {

    @Override
    public ValueSource parse(FunctionQParser fp) throws SyntaxError {

        String fieldName = fp.parseArg();

        String functionName = fp.parseArg();

        CompanyFunctionSortValueSource tvs = new CompanyFunctionSortValueSource(functionName, getValueSource(fp, fieldName));

        return tvs;
    }

    public ValueSource getValueSource(FunctionQParser fp, String arg) {
        if (arg == null)
            return null;
        SchemaField f = fp.getReq().getSchema().getField(arg);
        if (f.getType().getClass() == TrieDateField.class) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Can't use ms() function on non-numeric legacy date field " + arg);
        }
        return f.getType().getValueSource(f, fp);
    }
}
